import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

async function main() {
  await prisma.$executeRaw` delete from post; `;
  await prisma.$executeRaw` delete from user; `;
  // 1. 创建用户
  const user1 = await prisma.user.create({
    data: {
      email: "alice@example.com",
      name: "Alice",
    },
  });
  console.log("Created user:", user1);

  const user2 = await prisma.user.create({
    data: {
      email: "bob@example.com",
      name: "Bob",
    },
  });
  console.log("Created user:", user2);

  // 2. 创建帖子并关联用户
  const post1 = await prisma.post.create({
    data: {
      title: "Hello World",
      content: "This is my first post!",
      published: true,
      author: {
        connect: { id: user1.id }, // 关联用户Alice
      },
    },
  });
  console.log("Created post:", post1);

  const post2 = await prisma.post.create({
    data: {
      title: "Prisma is awesome",
      content: "Learning more about Prisma.",
      published: false,
      authorId: user2.id, // 另一种关联方式，直接使用外键
    },
  });
  console.log("Created post:", post2);

  // 3. 查询所有用户及其发布的帖子
  const usersWithPosts = await prisma.user.findMany({
    include: {
      posts: true, // 包含关联的帖子
    },
  });
  console.log("\nUsers with posts:");
  usersWithPosts.forEach((user) => {
    console.log(`- ${user.name} (${user.email})`);
    user.posts.forEach((post) => {
      console.log(`  - Title: ${post.title}, Published: ${post.published}`);
    });
  });

  // 4. 更新帖子
  const updatedPost = await prisma.post.update({
    where: { id: post2.id },
    data: { published: true },
  });
  console.log("\nUpdated post:", updatedPost);

  // 5. 删除用户及其相关帖子 (使用事务)
  // 注意：Prisma默认级联删除，但有些数据库可能需要手动配置ON DELETE CASCADE
  // 或者在应用层手动删除关联数据
  await prisma.$transaction([
    prisma.post.deleteMany({
      where: { authorId: user1.id },
    }),
    prisma.user.delete({
      where: { id: user1.id },
    }),
  ]);
  console.log(`\nDeleted user ${user1.name} and their posts.`);

  // 6. 再次查询确认
  const remainingUsers = await prisma.user.findMany();
  console.log("\nRemaining users:", remainingUsers);

  // 7. 原生sql

  const selectUserSql = "SELECT * FROM users ";
  const selectPostSql = "SELECT * FROM posts ";
  const rawUsers = async function runRawSql() {
    const users = await prisma.$executeRaw`${selectUserSql}`;
  };
  console.log("\nUsers from raw SQL:", rawUsers);
}

main()
  .catch((e) => {
    console.error(e);
  })
  .finally(async () => {
    await prisma.$disconnect(); // 断开数据库连接
  });
